<template>
  <div>
    <input type="text" placeholder="书名" v-model="bookName">
    <input type="text" placeholder="作者" v-model="author">
    <input type="text" placeholder="出版社" v-model="publisher">
    <button @click="onAdd">新增</button>
    <table>
      <tr>
        <th v-for="(item, i) in tableHead" :key="i">
          {{ item }}
        </th>
      </tr>
      <tr v-for="item in data" :key="item.id">
        <td v-for="(value, key) in item" :key="key">
          {{ value }}
        </td>
        <td>
          <button @click="onDel(item.id)">删除</button>
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
// import request from '../utils/request';
// API信息
const searchAPI = '/api/getbooks';
const addAPI = '/api/addbook';
const delAPI = '/api/delbook';

export default {
  data () {
    return {
      bookName: '',
      author: '',
      publisher: '',
      tableHead: ['id', '书名', '作者', '出版社', '操作'],
      data: [],
    };
  },
  // 数据刚刚初始化完成(完美请求)
  created () {
    this.search();
  },
  methods: {
    // 查
    async search () {
      const res = await this.req({
        method: 'get',
        url: searchAPI,
      });
      this.data = res.data.data;
    },
    // 添加
    async onAdd () {
      const res = await this.req({
        method: 'post',
        url: addAPI,
        data: {
          bookname: this.bookName,
          author: this.author,
          publisher: this.publisher,
        },
      });
      alert(res.data.msg);
      this.search();
    },
    // 删除
    async onDel (id) {
      const res = await this.req({
        method: 'get',
        url: delAPI,
        params: {
          id,
        },
      });
      alert(res.data.msg);
      this.search();
    },
  },
}
</script>

<style scoped>

</style>